<template>
  <a-modal v-model:open="open" title="新增试卷" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" style="margin-top: 16px">
      <a-form-item label="试卷名" name="name" :rules="[{ required: true, message: '请输入试卷名' }]">
        <a-input v-model:value="formState.name" placeholder="请输入试卷名" />
      </a-form-item>
      <a-form-item label="植物区域" name="areas">
        <a-select v-model:value="formState.areas" mode="multiple" placeholder="选择植物区域">
          <a-select-option :value="1">金佛山植物</a-select-option>
          <a-select-option :value="2">学校植物</a-select-option>
          <a-select-option :value="3">藏区植物</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="题目数量" name="num">
        <a-input v-model:value="formState.num" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" placeholder="请输入数量" />
      </a-form-item>
      <a-form-item label="关联分类" name="categorys">
        <a-select v-model:value="formState.categorys" mode="multiple" placeholder="选择关联分类">
          <a-select-option v-for="category in categoryList" :key="category.id" :value="category.id">
            {{ category.category_name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { fetchCategoryList } from '@/api/student'
import { fetchExamPaperGenerate } from '@/api/examPaper'
import { message } from 'ant-design-vue'

const emits = defineEmits(['refresh'])

const open = ref(false)
const handleOk = () => {
  formRef.value.validate().then(async () => {
    const res = await fetchExamPaperGenerate(formState.value)
    if (res.data.code === '200') {
      message.success('创建成功')
      emits('refresh')
      open.value = false
    } else {
      message.error(res.data.message)
    }
  })
}
const handleCancel = () => {
  Object.keys(formState.value).forEach(key => {
    formState.value[key] = undefined
  })
  open.value = false
}
const openModal = (record: any) => {
  if (record) {
    Object.keys(formState.value).forEach(key => {
      formState.value[key] = record[key]
    })
  }
  if (!categoryList.value.length) getCategoryList()
  open.value = true
}

// 关联分类数据
const categoryList = ref<{ id: number; category_name: string }[]>([])
const getCategoryList = async () => {
  const res = await fetchCategoryList({})
  categoryList.value = res.data.data.data
}

const formRef = ref()
const formState = ref<any>({
  id: undefined,
  name: undefined,
  areas: undefined,
  num: undefined,
  categorys: undefined,
})

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
